﻿using MediatR;
using SlaughterItem.Common.Domains.RBAC;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace GetSlaughterItem.API.Application.Commands.Week01.UsersCommends
{
    public class UserLoginHandler : IRequestHandler<UserLoginCommand, Result>
    {
        IBaseRepositoryGet<Users> UsersRep;
        IBaseRepositoryGet<Roles> RolesRep;

        public UserLoginHandler(IBaseRepositoryGet<Users> usersRep, IBaseRepositoryGet<Roles> rolesRep)
        {
            UsersRep = usersRep;
            RolesRep = rolesRep;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var userslist = UsersRep.GetAll().FirstOrDefault(x => x.UsersName == request.UsersName && x.UsersPwd == request.UsersPwd && x.IsDel == false);
                var rolelist = RolesRep.GetAll().FirstOrDefault(x => x.RolesId == userslist.RoleId);
                var list = new
                {
                    userslist.UsersId,
                    userslist.UsersName,
                    rolelist.RolesName,
                };
                if (list != null)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "登录成功";
                    result.Data = list;
                }
                else
                {
                    var list1 = new
                    {
                        UsersId = 0,
                        UsersName = "无",
                        RolesName = "无"
                    };
                    result.Code = (int)CommonErrorCode.Search;
                    result.Msg = "登录失败";
                    result.Data = list1;
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
